#include "app_schd_task.h"

#define SCHD_TASK_GET_TICK() GetTick()

static func_reg_info_t  schd;

void schd_task_register(func_callback_type func,uint32_t ms)
{
	static uint8_t init_ok = 0;
	if(!init_ok)
	{
		init_ok = 1;

		memset(&schd,0,sizeof(schd));
	}

	if(!func) return;
	
	func_reg_info_t *new_func_info;
	new_func_info = (func_reg_info_t *)malloc(sizeof(func_reg_info_t));
	if(!new_func_info) return;

	new_func_info->func_callback = func;
	new_func_info->delay_ms = ms;
	new_func_info->cur_tick = SCHD_TASK_GET_TICK();

	func_reg_info_t *ptr;
	ptr = &schd;
	
	new_func_info->reg_func_nums =  ptr->reg_func_nums;
	new_func_info->reg_func_nums++;

	if(ptr->reg_func_nums == 0)//the first
	{
		//ptr->next = (func_reg_info_t *)malloc(func_reg_info_t);
		//if(!ptr->next) return;

		//ptr->next = new_func_info;
		
		ptr->func_callback = func;
		ptr->cur_tick = SCHD_TASK_GET_TICK();
		ptr->delay_ms = ms;
		ptr->reg_func_nums++;
		
		ptr->next = 0;
	}
	else
	{
		while(ptr->next)//find full
		{
			ptr = ptr->next;
		}

		//ptr->next = (func_reg_info_t *)malloc(func_reg_info_t);
		//if(!ptr->next) return;
		
		ptr->next = new_func_info;
		ptr->next->next = 0;
	}
	
}

void schd_task_poll(void)
{
	func_reg_info_t *ptr;
	uint8_t poll_cnt = 0;

	ptr = &schd;

	while(ptr)
	{
		if(abs(ptr->cur_tick - SCHD_TASK_GET_TICK()) >= ptr->delay_ms)
		{
			ptr->cur_tick = SCHD_TASK_GET_TICK();

			ptr->func_callback();//callback	
		}
		ptr = ptr->next;

		poll_cnt++;
	}
}

